<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">管理员管理</span>
    <el-button type="primary" @click="addManager"
               style="float: right;margin-top:10px;">新增管理员
    </el-button>
  </div>

  <!-- 搜索卡片 -->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="管理员搜索">
        <el-input placeholder="输入姓名" style="width: 220px;"
                  v-model="searchManagerData.name"
                  @keydown.enter="loadManagerList"></el-input>
      </el-form-item>
      <el-form-item label="管理员状态" style="width: 290px;">
        <el-select placeholder="请选择状态" v-model="searchManagerData.status" @change="loadUser">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="-1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadManagerList">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 数据表格卡片 -->
  <el-card style="margin: 20px;">
<!--    <el-table :data="managerListData" v-loading="loading"-->
<!--              @select="selectManager"-->
<!--              @select-all="selectAllManager"-->
<!--    >-->
      <el-table :data="managerListData" v-loading="loading">
<!--      <el-table-column type="selection"></el-table-column>-->
      <el-table-column label="ID" prop="id" align="center" width="50"></el-table-column>
      <el-table-column label="姓名" prop="name" align="center"></el-table-column>
      <el-table-column label="联系方式" prop="phone" align="center"></el-table-column>
      <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
      <el-table-column label="权限组" prop="roleName" align="center"></el-table-column>
      <el-table-column label="状态" prop="status" align="center">
        <template #default="scope">
          <el-switch active-value="1" inactive-value="-1"
                     @change="changeManagerStatus(scope.row.id)"
                     v-model="scope.row.status"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="restPwd(scope.row.id)">重置密码</el-button>
          <el-button link type="primary" @click="editManager(scope.row.id)">编辑</el-button>
          <el-button link type="danger" @click="deleteManager(scope.row.id,scope.row.name)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--  分页-->
    <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalItems"
        @current-change="handleCurrentChange" style="margin-top: 20px;"/>
  </el-card>

  <el-dialog
      title="重置密码"
      style="width: 100vh;padding:40px;"
      v-model="dialogPwdVisible"
      :before-close="handlePwdClose"
  >
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="新密码">
            <el-input placeholder="请输入新密码" v-model="pwdData.password"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handlePwdClose">取消</el-button>
      <el-button type="primary" @click="savePwd">确定</el-button>
    </template>
  </el-dialog>

  <!-- 新建管理员弹窗 -->
  <!-- :before-close="handleClose"在弹窗关闭之前调用此自定义函数
   这样避免点击弹窗外部也能将弹窗关闭的问题 -->
  <el-dialog
      :title="dialogTitle"
      style="width: 100vh;padding:40px;"
      v-model="dialogVisible"
      :before-close="handleClose"
  >
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-input placeholder="请输入姓名" v-model="saveManagerData.name"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="联系方式">
            <el-input placeholder="请输入联系方式" v-model="saveManagerData.phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input placeholder="请输入邮箱地址" v-model="saveManagerData.email"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="权限组">
            <el-select placeholder="请选择权限组" v-model="saveManagerData.roleId">
              <el-option v-for="item in roleList" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="登录账号">
            <el-input placeholder="请输入管理端登录账号" v-model="saveManagerData.username"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="isEdit === false">
          <el-form-item label="登录密码">
            <el-input placeholder="请输入管理端登录密码" v-model="saveManagerData.password"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveManager">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
//管理员列表数据
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "@/api/axios";

//分页数据
const currentPage = ref(1);//当前页码
const pageSize = ref(15);//每页显示的条数
const totalItems = ref(0);//数据总数

//是否编辑状态,用于确定是否显示登录密码输入框
const isEdit = ref(false);

//监听跳转页码的事件
const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadManagerList();
}

//定义加载动画(true为加载,false为加载完成停止加载)
const loading = ref(true)

//列表数据
const managerListData = ref([])

//保存数据
const saveManagerData = ref({});
//弹窗标题
const dialogTitle = ref("新增管理员")

const dialogVisible = ref(false)

const dialogPwdVisible = ref(false);

const pwdData = ref({});

//搜索数据
const searchManagerData = ref({})

//权限组列表
const roleList = ref([])
onMounted(() => {
  loadManagerList();
})

//处理弹窗关闭的方法
const handleClose = () => {
  //用户确认关闭后,关闭弹窗
  dialogVisible.value = false;
  isEdit.value = false;
  //清空已输入的表单数据
  saveManagerData.value = {};
}

const handlePwdClose = () => {
  dialogPwdVisible.value = false;
  pwdData.value = {};
}

//点击新建的弹窗
const addManager = () => {
  dialogVisible.value = true;
  dialogTitle.value = "新增管理员";
  isEdit.value = false;
  getRoleList();
}

//加载列表
const loadManagerList = () => {
  loading.value = true;
  searchManagerData.value.page = currentPage.value
  searchManagerData.value.pageNum = pageSize.value
  axios.get('/v1/manager/list', {
    serviceName: 'managerService', params: searchManagerData.value
  }).then((response) => {
    if (response.data.code === 200) {
      managerListData.value = response.data.data.records;
      currentPage.value = response.data.data.current;
      totalItems.value = response.data.data.total;
      loading.value = false;
    } else {
      ElMessage.error(response.data.msg || "系统错误")
    }
  })
}

const ids = ref([])

//编辑管理员
const editManager = (id) => {
  dialogVisible.value = true;
  isEdit.value = true;
  dialogTitle.value = "编辑管理员";
  axios.get('/v1/manager/detail', {
    serviceName: 'managerService', params: {
      id: id,
    }
  }).then((response) => {
    if (response.data.code === 200) {
      getRoleList();
      saveManagerData.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取管理员信息失败");
    }
  })
};

//删除管理员
const deleteManager = (id, name) => {
  if (confirm("确定要删除【" + name + "】吗？")) {
    axios.delete("/v1/manager/delete", {
      serviceName: 'managerService', params: {
        id: id
      }
    }).then((response) => {
      if (response.data.code === 200) {
        ElMessage.success(response.data.msg || "删除成功");
        loadManagerList();
      } else {
        ElMessage.error(response.data.msg || "删除失败");
      }
    })
  }
};

//获取权限组
const getRoleList = () => {
  axios.get('/v1/role/api/getList', {serviceName: 'roleService'}).then((response) => {
    if (response.data.code === 200) {
      roleList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取权限组数据失败")
    }
  })
}

//更改管理员状态
const changeManagerStatus = (id) => {
  axios.get("/v1/manager/changeStatus", {
    serviceName: 'managerService', params: {
      id: id
    }
  }).then((response) => {
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || "修改成功");
    } else {
      ElMessage.error(response.data.msg || '修改失败')
    }
  })
}

//重置搜索方法
const resetSearch = () => {
  searchManagerData.value = {};
  loadManagerList();
}

/**
 * 保存数据
 */
const saveManager = () => {
  console.log(isEdit);
  let url = "/v1/manager/add";
  if (isEdit.value) {
    url = "/v1/manager/update";
  }
  axios.post(url, saveManagerData.value, {serviceName: 'managerService'}).then((response) => {
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || "保存成功");
      dialogVisible.value = false;
      loadManagerList();
    } else {
      ElMessage.error(response.data.msg || "保存失败")
    }
  })

}

//重置密码
const restPwd = (id) => {
  dialogPwdVisible.value = true;
  pwdData.value.id = id;
}

//重置密码保存
const savePwd = () => {
  axios.post("/v1/manager/resetPWD", pwdData.value, {serviceName: 'managerService'}).then((response) => {
    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || "重置密码成功");
      dialogPwdVisible.value = false;
      pwdData.value = {};
    } else {
      ElMessage.error(response.data.msg || "重置密码失败");
    }
  })
}

const selectManager = (data) => {
  data.forEach((item) => {
    ids.value.push(item.id)
  })
}

const selectAllManager = (data) => {
  data.forEach((item) => {
    ids.value.push(item.id)
  })
}
</script>

<style scoped>

</style>